import Vue from 'vue';
import Vuex from 'vuex';
import sideBar from '@/api/sideBar';
import goodsList from '@/api/goodsList';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    sideBar: [], // 侧边栏
    showContent: false,
    size: 5, // 固定显示5个
    goodsList: [], // 商品列表
    type: null,
    counterMap: {}, // {1, 5}即id为 1 的商品数量有 5 个

  },
  mutations: {
    // 根据id对应的num值来进行相应的操作
    setStorage(state, { id, value }) {
      if (state.counterMap[id]) {
        if (state.counterMap[id] === 1 && value === -1) {
          Vue.delete(state.counterMap, id);
        } else {
          Vue.set(state.counterMap, id, state.counterMap[id] + value);
        }
      } else {
        Vue.set(state.counterMap, id, 1);
      }
      localStorage.setItem('goods', JSON.stringify(state.counterMap));// 存储到本地
    },
    setCounterMap(state, payload) {
      state.counterMap = payload;
    },
    // 侧边栏
    setSideBar(state, payload) {
      state.sideBar = payload;
    },
    setShowContent(state, payload) {
      state.showContent = payload;
    },
    // 商品列表
    setGoodsList(state, payload) {
      // 因为不是传统意义上的翻页，而是新增数据进来
      state.goodsList = [...state.goodsList, ...payload];
    },
    resetGoodsList(state) {
      state.goodsList = [];
    },
    setGoodsType(state, payload) {
      state.type = payload;
    },
  },
  actions: {
    // 侧边栏
    async setSideBar(ctx, payload) {
      ctx.commit('setShowContent', false);
      const r = await sideBar(payload);
      ctx.commit('setSideBar', r);
      ctx.commit('setShowContent', true);
    },
    async setGoodsList(ctx, payload) {
      const { page, sortType } = payload;
      const type = payload.type || ctx.state.type;
      ctx.commit('setGoodsType', type);
      const r = await goodsList(type, page, ctx.state.size, sortType);
      //   console.log(r);
      ctx.commit('setGoodsList', r.list);
      if (r.total > ctx.state.goodsList.length) {
        return true;
      }
      return false;
    },
  },
  modules: {
  },
});
